<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getCameraListApi,
  createCameraApi,
  deleteCameraListApi,
  updateCameraApi,
  getCameraDetailApi
} from '@/api/device/camera/camera'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'

defineOptions({
  name: 'DeviceCamera'
})

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getCameraListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data || [],
      total: res.count || 0
    }
  },
  fetchDelApi: async (value) => {
    const res = await deleteCameraListApi(value)
    return res.code === 200
  }
})

const { dataList, loading, total, pageSize, currentPage } = tableState
const { getList, delList } = tableMethods

const statusOptions = [
  { label: '在线', value: 'online' },
  { label: '离线', value: 'offline' },
  { label: '维护中', value: 'maintenance' }
]

const getStatusLabel = (status: string) => {
  const option = statusOptions.find((opt) => opt.value === status)
  return option ? option.label : status
}

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'id',
    label: '编号',
    show: true,
    disabled: false
  },
  {
    field: 'serial_number',
    label: '序列号',
    show: true,
    disabled: true
  },
  {
    field: 'model',
    label: '型号',
    show: true
  },
  {
    field: 'ip_address',
    label: 'IP地址',
    show: true
  },
  {
    field: 'status',
    label: '状态',
    show: true,
    slots: {
      default: (data: any) => {
        const row = data.row
        const status = row.status
        let type = ''

        switch (status) {
          case 'online':
            type = 'success'
            break
          case 'offline':
            type = 'danger'
            break
          case 'maintenance':
            type = 'warning'
            break
          default:
            type = 'info'
        }

        return (
          <>
            <el-tag type={type}>{getStatusLabel(status)}</el-tag>
          </>
        )
      }
    }
  },
  {
    field: 'last_active',
    label: '最后活动时间',
    show: true
  },
  {
    field: 'room_id',
    label: '房间ID',
    show: true
  },
  {
    field: 'action',
    width: '170px',
    label: '操作',
    show: true,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" link size="small" onClick={() => editAction(row)}>
              编辑
            </BaseButton>
            <BaseButton
              type="danger"
              loading={delLoading.value}
              link
              size="small"
              onClick={() => delData(row)}
            >
              删除
            </BaseButton>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'serial_number',
    label: '序列号',
    component: 'Input',
    componentProps: {
      clearable: true,
      style: {
        width: '214px'
      }
    }
  },
  {
    field: 'model',
    label: '型号',
    component: 'Input',
    componentProps: {
      clearable: true,
      style: {
        width: '214px'
      }
    }
  },
  {
    field: 'status',
    label: '状态',
    component: 'Select',
    componentProps: {
      style: {
        width: '214px'
      },
      options: statusOptions,
      clearable: true
    }
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  currentPage.value = 1
  searchParams.value = data
  getList()
}

const delLoading = ref(false)

const delData = async (row: any) => {
  delLoading.value = true
  await delList(true, [row.id]).finally(() => {
    delLoading.value = false
  })
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref<'add' | 'edit'>('add')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const editAction = async (row: any) => {
  try {
    const res = await getCameraDetailApi(row.id)
    if (res) {
      dialogTitle.value = '编辑摄像头'
      actionType.value = 'edit'
      currentRow.value = res.data
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取摄像头数据失败', error)
  }
}

const addAction = () => {
  dialogTitle.value = '新增摄像头'
  actionType.value = 'add'
  currentRow.value = undefined
  dialogVisible.value = true
}

const save = async () => {
  const write = unref(writeRef)
  const valid = await write?.validate()

  if (valid) {
    console.log(writeRef, write, unref(write))
    const formData = await write?.getFormData()

    if (formData) {
      saveLoading.value = true
      try {
        let res
        if (actionType.value === 'add') {
          res = await createCameraApi(formData)
          if (res && res.code === 200) {
            dialogVisible.value = false
            getList()
          }
        } else if (actionType.value === 'edit') {
          res = await updateCameraApi(formData.id!, formData)
          if (res && res.code === 200) {
            dialogVisible.value = false
            getList()
          }
        }
      } finally {
        saveLoading.value = false
      }
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      showAction
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
      @refresh="getList"
    >
      <template #toolbar>
        <ElRow :gutter="10">
          <ElCol :span="1.5">
            <BaseButton type="primary" @click="addAction">新增摄像头</BaseButton>
          </ElCol>
        </ElRow>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write ref="writeRef" :current-row="currentRow" :action-type="actionType" />

    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
